﻿using ERPWinFormWork.Product.Model;
using ERPWinFormWork.Product.ProductDtos;
using ERPWinFormWork.Product.ProductErrorCode;
using ERPWinFormWork.Sales;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Product
{
    public partial class ProductIn : Form
    {
        private ApiClient _apiClient; 
        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private int TotalPages { get; set; } = 1;
        private int TotalSize { get; set; }


        public ProductIn()
        {
            InitializeComponent();
            // 初始化 API 客户端（替换为你的实际 API 基础地址）
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);
            GetData();




            


        }


        /// <summary>
        /// 新增入库按钮跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 新增入库ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StockinAdd stockin = new StockinAdd();
            stockin.Show();

        }
        /// <summary>
        /// 新增入库按钮跳转
        /// </summary>
        private void btnaddoutproduct_Click(object sender, EventArgs e)
        {
            StockinAdd stockin = new StockinAdd();
            stockin.Show();
        }

        /// <summary>
        /// 入库信息的显示
        /// </summary>
        private async void GetData()
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },

                    //{ "Stockin_Name", this.skinTextBox5.Text },
                    //{ "Stockin_Number", this.textinspectionNode.Text },
                    //{ "Batch", this.skinTextBox4.Text },
                    //{ "Product_Name", this.skinTextBox3.Text },
                    //{ "Work_Name", this.skinTextBox1.Text },
                    //{ "Work_Number", this.skinTextBox2.Text },
                    //{ "Warehouse_Name", this.comboBox2.Text },
                    // 1. 文本框：Trim() + 非空才传递
                    //{ "Stockin_Name", this.skinTextBox5.Text.Trim() },
                    //{ "Stockin_Number", this.textinspectionNode.Text.Trim() }, // 加Trim()
                    //{ "Batch", this.skinTextBox4.Text.Trim() },
                    //{ "Product_Name", this.skinTextBox3.Text.Trim() },
                    //{ "Work_Name", this.skinTextBox1.Text.Trim() }, // 加Trim()
                    //{ "Work_Number", this.skinTextBox2.Text.Trim() },
                    //// 2. 日期：统一格式（根据后端要求调整，如只传日期不含时间）
                    //{ "Stockin_Time", this.dateTimePicker1.Value.ToString("yyyy-MM-dd") }, 
                    //// 3. 下拉框：判断是否选中有效项（避免传递空或默认提示）
                    //{ "Warehouse_Name", comboBox2.SelectedItem != null ? ((Warehouse_Model)comboBox2.SelectedItem).Warehouse_Name : "" }


                };


            var response = await _apiClient.GetAsync<ApiResult<List<StockinDtos>>>(
                    endpoint: "Product/DiscountGet",
                    parameters: parameters
                );
            if (response != null && response.code == 200)
            {
                dgvGetDiscount.DataSource = response.pageData;
                TotalPages = response.totaCount;
                TotalSize = Convert.ToInt32(Math.Ceiling(TotalPages * 1.0 / PageSize));
                this.lblcount.Text = TotalSize.ToString();
                AddOperationColumns();
            }
        }

        /// <summary>
        /// 上一页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrevPage_Click_1(object sender, EventArgs e)
        {
            if (PageIndex > 1)
            {
                PageIndex--;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }

        /// <summary>
        /// 下一页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextPage_Click_1(object sender, EventArgs e)
        {
            if (PageIndex < TotalSize)
            {
                PageIndex++;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }

        private void AddOperationColumns()
        {
            string[] columnNames = { "Details", "Edit", "Delete","Update" };
            string[] headerTexts = { "详情", "编辑", "删除","状态" };

            for (int i = 0; i < columnNames.Length; i++)
            {
                if (dgvGetDiscount.Columns[columnNames[i]] == null)
                {
                    var col = new DataGridViewButtonColumn();
                    col.Name = columnNames[i];
                    col.HeaderText = headerTexts[i];
                    col.Text = headerTexts[i];
                    col.UseColumnTextForButtonValue = true;
                    dgvGetDiscount.Columns.Add(col);
                }
            }
        }

        private async void dgvGetDiscount_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                StockinDtos item = dgvGetDiscount.Rows[e.RowIndex].DataBoundItem as StockinDtos;
                if (item != null)
                {
                    string colName = dgvGetDiscount.Columns[e.ColumnIndex].Name;
                    if (colName == "Details")
                    {
                        new DiscountDetailsForm(item.Id).ShowDialog();
                    }
                    else if (colName == "Edit")
                    {
                        //new DiscountAddForm(this, DiscountAddForm.Mode.Edit, item.Id).ShowDialog();
                        //GetData();
                    }
                    else if (colName == "Update")
                    {
                        var data = new { id = item.Id, Stockin_State = 1 };
                        var response = await _apiClient.PostAsync<object, ApiResult<string>>("Product/StateStockin", data);

                        if (response != null && response.code == 200)
                        {
                            MessageBox.Show("已修改入库状态", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            GetData();
                        }
                        else
                        {
                            MessageBox.Show($"修改入库状态失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else if (colName == "Delete")
                    {
                        if (MessageBox.Show("确认删除此折扣方案?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            var data = new { id = item.Id };
                            var response = await _apiClient.PostAsync<object, ApiResult<string>>("Product/DelStockin", data);
                            if (response != null && response.code == 200)
                            {
                                MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                GetData();
                            }
                            else
                            {
                                MessageBox.Show($"删除失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }

                }
            }
        }


        /// <summary>
        /// 导出按钮设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void skinButton1_Click(object sender, EventArgs e)
        {
            var parameters = new Dictionary<string, string>
            {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    //{ "Name", this.txtDiscountName.Text.Trim() },
                    //{ "Createtime", this.dtpCreateTime.Text },
            };

            // Assuming export endpoint is Sales/DiscountExport and returns ApiResponse<string> with file path or message
            byte[] excelBytes = await _apiClient.GetBytesAsync(
            endpoint: "Product/GetSortShow", // 后端导出接口名（与 [HttpGet("DiscountGetExport")] 匹配）
            parameters: parameters
             );

            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*"; // 只允许保存xlsx格式
                saveDialog.Title = "保存折扣方案导出文件";
                // 默认文件名：与后端一致（带时间戳，避免重复）
                saveDialog.FileName = $"产品入库信息_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                saveDialog.RestoreDirectory = true; // 打开时默认显示上次保存的路径

                // 若用户选择了保存路径
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 将二进制流写入本地文件（完成保存）
                        System.IO.File.WriteAllBytes(saveDialog.FileName, excelBytes);

                        // 导出成功提示 + 可选打开文件
                        DialogResult openChoice = MessageBox.Show(
                            $"导出成功！\n文件已保存到：\n{saveDialog.FileName}\n是否立即打开文件？",
                            "导出成功",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                        );

                        if (openChoice == DialogResult.Yes)
                        {
                            // 用系统默认程序（如WPS/Office）打开Excel
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // 处理“无保存权限”错误（如选择C盘根目录）
                        MessageBox.Show("导出失败：没有文件保存权限！请选择桌面或其他有权限的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (System.IO.IOException ex)
                    {
                        // 处理“文件被占用”错误（如Excel已打开）
                        MessageBox.Show($"导出失败：文件被占用！\n原因：{ex.Message}\n请先关闭已打开的同名Excel文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        /// <summary>
        /// 跳转按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 销售出库ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StockoutShow stockoutShow = new StockoutShow();
            stockoutShow.Show();
        }

        private void 产品库存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InventoryShow inventoryShow = new InventoryShow();
            inventoryShow.Show();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchoutproduct_Click(object sender, EventArgs e)
        {
            GetData();
        }

        private void skinTextBox1_Paint(object sender, PaintEventArgs e)
        {
           
        }

        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnqclick_Click(object sender, EventArgs e)
        {
            
            //skinTextBox5.Text.Clone();
            //textinspectionNode.Text.Clone();
            //skinTextBox4.Text.Clone();
            //skinTextBox3.Text.Clone();
            //skinTextBox2.Text.Clone();
            //skinTextBox1.Text.Clone();
            GetData();

        }

        /// <summary>
        /// 采购单跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 采购单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PurchaseShow purchaseShow = new PurchaseShow();
            purchaseShow.Show();
        }

        /// <summary>
        /// 仓库查询
        /// </summary>
        //private async void GetProductSelect5()
        //{
        //    var response = await _apiClient.GetAsync<ApiResult<List<Warehouse_Model>>>(
        //            endpoint: "Product/WareHouseShow"
        //        );
        //    if (response != null)
        //    {
        //        comboBox2.DataSource = response.data;
        //        comboBox2.DisplayMember = "Warehouse_Name";//指定显示的字段
        //        comboBox2.ValueMember = "id";//绑定id属性
        //    }
        //}


        //private async Task GetProductSelect5() // 改为Task返回值
        //{
        //    var response = await _apiClient.GetAsync<ApiResult<List<Warehouse_Model>>>(
        //        endpoint: "Product/WareHouseShow"
        //    );
        //    if (response != null && response.code == 200) // 加code判断，确保数据有效
        //    {
        //        comboBox2.DataSource = response.data;
        //        comboBox2.DisplayMember = "Warehouse_Name";
        //        comboBox2.ValueMember = "id";
        //        // 可选：设置默认选中第一项（避免空值）
        //        if (comboBox2.Items.Count > 0)
        //            comboBox2.SelectedIndex = 0;
        //    }
        //    else
        //    {
        //        MessageBox.Show($"仓库数据加载失败：{response?.msg ?? "未知错误"}", "提示");
        //    }
        //}




    }
}
